import React, { useState } from 'react';
import { Upload, Button, Table, message, Select, Card, Typography, Space } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx'; // Import xlsx library
import { adminAPI } from '../services/api'; // Assume your API calls are here

// Import Lucide React icons
import { CloudUpload, FolderKanban, FileText, Info, CheckCircle, XCircle } from 'lucide-react';


const { Option } = Select;
const { Text, Title } = Typography;

const BulkImport = () => {
    const [fileList, setFileList] = useState([]);
    const [previewData, setPreviewData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [importType, setImportType] = useState('room'); // Default import type is room
    const [invalidRowCount, setInvalidRowCount] = useState(0); // State to track invalid rows

    // Define column configurations for different import types
    const getColumns = (type) => {
        switch (type) {
            case 'room':
                return [
                    { title: '房间号', dataIndex: 'room_number', key: 'room_number' },
                    { title: '房间类型', dataIndex: 'room_type', key: 'room_type' },
                    { title: '床位数', dataIndex: 'beds', key: 'beds' },
                    { title: '价格', dataIndex: 'price', key: 'price', render: price => `¥${parseFloat(price).toFixed(2)}` },
                ];
            case 'menuItem':
                return [
                    { title: '商品名称', dataIndex: 'item_name', key: 'item_name' },
                    { title: '价格', dataIndex: 'price', key: 'price', render: price => `¥${parseFloat(price).toFixed(2)}` },
                    { title: '分类', dataIndex: 'category', key: 'category' },
                ];
            default:
                return [];
        }
    };

    // Define Excel format requirements for different import types
    const getFormatRequirements = (type) => {
        switch (type) {
            case 'room':
                return (
                    <ul className="list-disc list-inside space-y-2 text-gray-700 text-base">
                        <li>第一行应为标题行：<Text code className="font-mono bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm">房间号, 房间类型, 床位数, 价格</Text></li>
                        <li>房间类型：<Text code className="font-mono bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm">标准间/大床房/套房</Text></li>
                        <li>床位数：整数（如 <Text code className="font-mono bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm">2</Text>）</li>
                        <li>价格：数字（如 <Text code className="font-mono bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm">300.00</Text>）</li>
                    </ul>
                );
            case 'menuItem':
                return (
                    <ul className="list-disc list-inside space-y-2 text-gray-700 text-base">
                        <li>第一行应为标题行：<Text code className="font-mono bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm">商品名称, 价格, 分类</Text></li>
                        <li>价格：数字（如 <Text code className="font-mono bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm">15.50</Text>）</li>
                        <li>分类：可选，如 <Text code className="font-mono bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm">食品/饮料/服务</Text></li>
                    </ul>
                );
            default:
                return null;
        }
    };

    const handleFileUpload = (file) => {
        setLoading(true); // Set loading state when starting to read file
        setFileList([file]); // Set file list, keep only the current uploaded file
        setPreviewData([]); // Clear previous preview data
        setInvalidRowCount(0); // Reset invalid row count
        const reader = new FileReader();

        reader.onload = (e) => {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' }); // Parse workbook

                const sheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[sheetName];

                const json = XLSX.utils.sheet_to_json(worksheet, { header: 1, raw: false });

                if (json.length === 0) {
                    message.error('文件内容为空或格式不正确！');
                    setFileList([]);
                    setLoading(false);
                    return;
                }

                const headers = json[0];
                let rows = json.slice(1); // Get data rows

                let parsedData = [];
                let isValidFileHeader = true; // Flag for file header validation
                let expectedHeaders = []; // Dynamic expected headers

                // Set expected headers and perform initial validation and parsing based on import type
                switch (importType) {
                    case 'room':
                        expectedHeaders = ['房间号', '房间类型', '床位数', '价格'];
                        if (!headers || headers.length !== expectedHeaders.length || !expectedHeaders.every((val, index) => String(headers[index]).trim() === val)) {
                            message.error('房间导入文件标题行不正确！请确保是 "房间号, 房间类型, 床位数, 价格"。');
                            isValidFileHeader = false;
                        } else {
                            rows = rows.filter(row => row[0] !== undefined && row[0] !== null && String(row[0]).trim() !== '');
                            parsedData = rows.map((row, index) => ({
                                key: `preview-${index}`,
                                room_number: String(row[0] || '').trim(),
                                room_type: String(row[1] || '').trim(),
                                beds: parseInt(row[2], 10) || 0,
                                price: parseFloat(row[3]) || 0.00,
                            }));
                        }
                        break;
                    case 'menuItem':
                        expectedHeaders = ['商品名称', '价格']; // Category is optional
                        if (!headers || headers.length < 2 || String(headers[0]).trim() !== '商品名称' || String(headers[1]).trim() !== '价格') {
                            message.error('商品导入文件标题行不正确！请确保至少是 "商品名称, 价格"。');
                            isValidFileHeader = false;
                        } else {
                            rows = rows.filter(row => row[0] !== undefined && row[0] !== null && String(row[0]).trim() !== ''); // Item name cannot be empty
                            parsedData = rows.map((row, index) => ({
                                key: `preview-${index}`,
                                item_name: String(row[0] || '').trim(),
                                price: parseFloat(row[1]) || 0.00,
                                category: String(row[2] || '').trim() || null, // Category optional
                            }));
                        }
                        break;
                    default:
                        message.error('未知的导入类型！');
                        isValidFileHeader = false;
                }

                if (!isValidFileHeader) {
                    setFileList([]);
                    setLoading(false);
                    return;
                }

                if (parsedData.length === 0) {
                    message.error('文件中没有有效的可导入数据！');
                    setFileList([]);
                    setLoading(false);
                    return;
                }

                // Add more strict business logic validation, e.g., ID card length, phone number format
                const invalidCount = parsedData.filter(item => {
                    if (importType === 'room') {
                        return !item.room_number || !item.room_type || isNaN(item.beds) || item.beds <= 0 || isNaN(item.price) || item.price < 0;
                    } else if (importType === 'menuItem') {
                        return !item.item_name || isNaN(item.price) || item.price < 0;
                    }
                    return false;
                }).length;

                setInvalidRowCount(invalidCount);

                if (invalidCount > 0) {
                    message.warn(`部分导入数据格式不正确（共 ${invalidCount} 条），请检查预览数据！`);
                }

                setPreviewData(parsedData);
                message.success(`${file.name} 文件读取成功，请预览并点击“开始导入”！`);
            } catch (error) {
                console.error('解析Excel文件失败:', error);
                message.error('文件解析失败，请检查文件格式。');
                setPreviewData([]);
                setFileList([]);
            } finally {
                setLoading(false); // Cancel loading state after file reading is complete
            }
        };

        reader.onerror = () => {
            message.error('文件读取失败！');
            setLoading(false);
        };

        reader.readAsArrayBuffer(file); // Key: Use readAsArrayBuffer
        return false; // Prevent Ant Design from auto-uploading
    };

    const handleStartImport = async () => {
        if (previewData.length === 0) {
            message.warn('没有数据可以导入！请先选择并解析Excel文件。');
            return;
        }

        setLoading(true);
        try {
            let response;
            // Call different APIs based on import type
            if (importType === 'room') {
                response = await adminAPI.bulkImportRooms(previewData.map(item => ({
                    room_number: item.room_number,
                    room_type: item.room_type,
                    beds: item.beds,
                    price: item.price,
                })));
            } else if (importType === 'menuItem') {
                response = await adminAPI.bulkImportMenuItems(previewData.map(item => ({
                    item_name: item.item_name,
                    price: item.price,
                    category: item.category,
                })));
            } else {
                message.error('请选择导入类型！');
                setLoading(false);
                return;
            }

            // Handle response uniformly, Ant Design's message.success needs a string
            message.success(response.data.message || `成功导入 ${response.data.importedCount || 0} 条数据！`);
            setPreviewData([]);
            setFileList([]);
            setInvalidRowCount(0); // Reset invalid row count after successful import
        } catch (error) {
            console.error('批量导入失败:', error);
            // More detailed error message
            message.error(error.response?.data?.message || error.response?.data?.error || '批量导入失败: 未知错误');
        } finally {
            setLoading(false);
        }
    };

    const columns = getColumns(importType); // Get column configuration based on current import type
    const formatRequirements = getFormatRequirements(importType); // Get format requirements based on current import type

    return (
        <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-8 font-inter antialiased flex items-center justify-center">
            <Card
                title={
                    <span className="flex items-center text-4xl font-extrabold text-gray-800">
                        <CloudUpload className="w-12 h-12 mr-4 text-blue-600" />
                        批量导入数据
                    </span>
                }
                className="w-full max-w-5xl mx-auto bg-white rounded-3xl shadow-2xl p-10 transform transition-all duration-500 hover:scale-[1.01]"
                bordered={false} // Remove default Ant Design border for cleaner look
                headStyle={{ borderBottom: 'none', paddingBottom: '20px' }}
                bodyStyle={{ paddingTop: '0px' }}
            >
                <div className="mb-8 flex items-center">
                    <Title level={4} className="text-xl text-gray-700 mr-6 flex items-center mb-0">
                        <FolderKanban className="w-6 h-6 mr-3 text-purple-600" />
                        选择导入类型：
                    </Title>
                    <Select
                        value={importType}
                        onChange={(value) => {
                            setImportType(value);
                            setFileList([]); // Clear file and preview data when switching types
                            setPreviewData([]);
                            setInvalidRowCount(0); // Reset invalid row count
                        }}
                        className="w-60 rounded-xl shadow-md"
                        size="large" // Make select larger
                    >
                        <Option value="room" className="text-base py-2">房间数据</Option>
                        <Option value="menuItem" className="text-base py-2">商品数据</Option>
                    </Select>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-10">
                    {/* Excel Format Requirements Card */}
                    <Card
                        className="bg-blue-50 border border-blue-200 rounded-2xl shadow-inner p-6 flex flex-col justify-between"
                        bordered={false}
                    >
                        <Title level={4} className="text-blue-800 flex items-center mb-4">
                            <FileText className="w-6 h-6 mr-3 text-blue-600" />
                            Excel 文件格式要求
                        </Title>
                        {formatRequirements}
                    </Card>

                    {/* Import Status/Info Card */}
                    <Card
                        className="bg-green-50 border border-green-200 rounded-2xl shadow-inner p-6 flex flex-col justify-between"
                        bordered={false}
                    >
                        <Title level={4} className="text-green-800 flex items-center mb-4">
                            <Info className="w-6 h-6 mr-3 text-green-600" />
                            导入状态概览
                        </Title>
                        <ul className="list-none space-y-2 text-gray-700 text-base">
                            <li className="flex items-center">
                                {fileList.length > 0 ? <CheckCircle className="w-5 h-5 mr-2 text-green-500" /> : <XCircle className="w-5 h-5 mr-2 text-red-500" />}
                                文件已选择: <Text strong className="ml-2">{fileList.length > 0 ? fileList[0].name : '未选择'}</Text>
                            </li>
                            <li className="flex items-center">
                                {previewData.length > 0 ? <CheckCircle className="w-5 h-5 mr-2 text-green-500" /> : <XCircle className="w-5 h-5 mr-2 text-red-500" />}
                                预览数据条数: <Text strong className="ml-2">{previewData.length}</Text>
                            </li>
                            {invalidRowCount > 0 && (
                                <li className="flex items-center text-red-600">
                                    <XCircle className="w-5 h-5 mr-2 text-red-500" />
                                    无效数据条数: <Text strong className="ml-2">{invalidRowCount}</Text>
                                </li>
                            )}
                            <li className="flex items-center">
                                <Info className="w-5 h-5 mr-2 text-blue-500" />
                                导入类型: <Text strong className="ml-2">{importType === 'room' ? '房间数据' : '商品数据'}</Text>
                            </li>
                        </ul>
                    </Card>
                </div>


                <div className="flex flex-col sm:flex-row items-center justify-center gap-6 mb-10">
                    <Upload
                        accept=".xlsx, .xls"
                        beforeUpload={handleFileUpload} // Use custom upload handler
                        fileList={fileList}
                        onRemove={() => { setFileList([]); setPreviewData([]); setInvalidRowCount(0); }}
                        maxCount={1} // Allow only one file upload
                        showUploadList={false} // Hide default upload list, we'll show status in card
                    >
                        <Button
                            icon={<UploadOutlined className="text-xl" />}
                            className="w-64 h-16 bg-gradient-to-r from-gray-200 to-gray-300 text-gray-800 font-bold text-lg rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1 hover:scale-105 border-none flex items-center justify-center"
                            size="large"
                        >
                            选择Excel文件
                        </Button>
                    </Upload>
                    <Button
                        type="primary"
                        onClick={handleStartImport}
                        disabled={previewData.length === 0 || loading}
                        loading={loading}
                        className="w-64 h-16 bg-gradient-to-r from-green-500 to-green-600 text-white font-bold text-lg rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1 hover:scale-105 border-none flex items-center justify-center"
                        size="large"
                    >
                        开始导入
                    </Button>
                </div>

                {previewData.length > 0 && (
                    <div className="mt-8">
                        <Title level={4} className="mb-6 text-2xl text-gray-700 flex items-center">
                            <FileText className="w-6 h-6 mr-3 text-blue-600" />
                            预览数据 ({previewData.length} 条):
                        </Title>
                        <Table
                            columns={columns} // Use dynamic column configuration
                            dataSource={previewData}
                            pagination={{
                                pageSize: 10,
                                showSizeChanger: true,
                                showQuickJumper: true,
                                pageSizeOptions: ['10', '20', '50', '100'],
                                showTotal: (total, range) => `显示 ${range[0]}-${range[1]} 共 ${total} 条`,
                            }} // Add pagination
                            bordered
                            rowKey="key" // Use internally generated key
                            scroll={{ x: 'max-content' }} // Ensure table is scrollable when content is wide
                            className="rounded-xl shadow-xl overflow-hidden"
                            size="large" // Make table larger
                        />
                    </div>
                )}
            </Card>
        </div>
    );
};

export default BulkImport;
